<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\common\model\store;

use app\common\model\Region as RegionModel;
use cores\BaseModel;

/**
 * 商家门店模型
 * Class Shop
 * @package app\common\model\store
 */
class Shop extends BaseModel
{
    // 定义表名
    protected $name = 'store_shop';

    // 定义主键
    protected $pk = 'shop_id';

    /**
     * 文章详情：HTML实体转换回普通字符
     * @param $value
     * @return string
     */
    public function getContentAttr($value)
    {
        return $value ? htmlspecialchars_decode($value) : '';
    }
    public function getParkAttr($value)
    {
        return $value ? htmlspecialchars_decode($value) : '';
    }
    public function getTagsAttr($value)
    {
        return $value ? explode(';', $value) : [];
    }
    public function getEndDateAttr($value)
    {
        return $value ? Date('Y-m-d', $value) : '';
    }

    /**
     * 追加字段
     * @var array
     */
    protected $append = ['version_text','value', 'label', 'cascader', 'region', 'full_address', 'coordinate', 'qrcode', 'shop_hours', 'day'];

    public function getVersionTextAttr($value, $data)
    {
        switch ($data['version']) {
            case 1:
                $version = '免费版';
                break;
            case 2:
                $version = '基础版';
                break;
            case 3:
                $version = '高级版';
                break;

            default:
                // code...
                break;
        }

        return $version;
    }
    public function getLabelAttr($value, $data)
    {

        return $data['shop_name'];
    }
    public function getValueAttr($value, $data)
    {

        return $data['shop_id'];
    }
    public function getDayAttr($value, $data)
    {
        if ($data['end_date'] < time()) {
            $day = 0;
        } else {
            $day = round(($data['end_date'] - time()) / 86400);
        }

        return $day;
    }
    public function getShopHoursAttr($value, $data)
    {

        return $data['start_time'] . '-' . $data['end_time'];
    }

    public function getQrcodeAttr($value, $data)
    {
        $url = base_url();
        return $url . 'temp/qrcode/shop_' . $data['shop_id'] . '.png';
    }
    public function parkImage()
    {
        $module = self::getCalledModule();
        return $this->hasOne("app\\{$module}\\model\\UploadFile", 'file_id', 'park_id')
            ->bind(['park_url' => 'preview_url']);
    }
    public function floatImage()
    {
        $module = self::getCalledModule();
        return $this->hasOne("app\\{$module}\\model\\UploadFile", 'file_id', 'float_id')
            ->bind(['float_url' => 'preview_url']);
    }
    /**
     * 关联文章封面图
     * @return \think\model\relation\HasOne
     */
    public function logoImage()
    {
        $module = self::getCalledModule();
        return $this->hasOne("app\\{$module}\\model\\UploadFile", 'file_id', 'logo_image_id')
            ->bind(['logo_url' => 'preview_url']);
    }
    public function cardImage()
    {
        $module = self::getCalledModule();
        return $this->hasOne("app\\{$module}\\model\\UploadFile", 'file_id', 'card_file_id')
            ->bind(['card_image_url' => 'preview_url']);
    }
    public function vrImage()
    {
        $module = self::getCalledModule();
        return $this->hasOne("app\\{$module}\\model\\UploadFile", 'file_id', 'vr_image_id')
            ->bind(['vr_image_url' => 'preview_url']);
    }
    public function vrVideo()
    {
        $module = self::getCalledModule();
        return $this->hasOne("app\\{$module}\\model\\UploadFile", 'file_id', 'video_id')
        ;
    }
    public function images()
    {
        $module = self::getCalledModule();
        return $this->hasMany("app\\{$module}\\model\\ding\\ShopImages", 'shop_id', 'shop_id')
        ;
    }
    public function advImages()
    {
        $module = self::getCalledModule();
        return $this->hasMany("app\\{$module}\\model\\ding\\ShopAdvImages", 'shop_id', 'shop_id')
        ;
    }
    //招牌菜
    public function dish()
    {
        $module = self::getCalledModule();
        return $this->hasMany("app\\{$module}\\model\\ding\\ShopDish", 'shop_id', 'shop_id')
        ;
    }

    public function types()
    {
        $module = self::getCalledModule();
        return $this->hasMany("app\\{$module}\\model\\ding\\ShopTypeRel", 'shop_id', 'shop_id')
        ;
    }

    public function daili()
    {
        $module = self::getCalledModule();
        return $this->hasOne("app\\{$module}\\model\\ding\\Daili", 'clerk_id', 'daili_id')
        ;
    }

    //菜系

    public function foods()
    {
        $module = self::getCalledModule();
        return $this->hasMany("app\\{$module}\\model\\ding\\ShopFoodsRel", 'shop_id', 'shop_id')
        ;
    }
    /**
     * 获取器：省市区id集
     * @param $value
     * @param $data
     * @return array
     */
    public function getCascaderAttr($value, $data)
    {
        return [$data['province_id'], $data['city_id'], $data['region_id']];
    }

    /**
     * 获取器：省市区名称集
     * @param $value
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getRegionAttr($value, $data)
    {
        return $this->getRegionNames($data);
    }

    /**
     * 获取器：获取完整地址
     * @param $value
     * @param $data
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getFullAddressAttr($value, $data)
    {
        $rgionNames = $this->getRegionNames($data);
        return "{$rgionNames['province']}{$rgionNames['city']}{$rgionNames['region']}{$data['address']}";
    }

    /**
     * 获取器：坐标经纬度
     * @param $value
     * @param $data
     * @return string
     */
    public function getCoordinateAttr($value, $data)
    {
        return "{$data['latitude']},{$data['longitude']}";
    }

    /**
     * 获取省市区名称
     * @param array $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getRegionNames(array $data)
    {
        static $dataset = [];
        $id             = $data[$this->getPk()];
        if (! isset($dataset[$id])) {
            $dataset[$id] = [
                'province' => RegionModel::getNameById($data['province_id']),
                'city'     => RegionModel::getNameById($data['city_id']),
                'region'   => RegionModel::getNameById($data['region_id']),
            ];
        }
        return $dataset[$id];
    }

    /**
     * 门店详情
     * @param int $shopId 门店ID
     * @param array $with 关联查询
     * @return static|null
     */
    public static function detail(int $shopId, array $with = [])
    {
        return static::get($shopId, $with);
    }

    /**
     * 累积用户可用余额
     * @param int $userId
     * @param float $money
     * @return mixed
     */
    public static function setIncBalance(int $shopId, float $money)
    {
        return (new static )->setInc($shopId, 'balance', $money);
    }

    /**
     * 消减用户可用余额
     * @param int $userId
     * @param float $money
     * @return mixed
     */
    public static function setDecBalance(int $shopId, float $money)
    {
        return (new static )->setDec([['shop_id', '=', $shopId]], 'balance', $money);
    }

    /**
     * 累积商家金额-用户消费获得
     * @param int $userId
     * @param float $money
     * @return mixed
     */
    public static function setIncMoney(int $shopId, float $money)
    {
        return (new static )->setInc($shopId, 'pay_money', $money);
    }

}
